﻿/*!

 @Title: swui
 @Description：Win10风格前端模板
 @Site: www.win-ui.com
 @Author: Leo
 @License：MIT

 */

; !function () {
    "use strict";
    var userAction = false;
    var getPath = function () {
        var doc = document;
        var jsPath = doc.currentScript ? doc.currentScript.src : function () {
            var js = doc.scripts
                , last = js.length - 1
                , src;
            for (var i = last; i > 0; i--) {
                if (js[i].readyState === 'interactive') {
                    src = js[i].src;
                    break;
                }
            }
            return src || js[last].src;
        }();
        return jsPath.substring(0, jsPath.lastIndexOf('/') + 1);
    }();

    layui.define(['jquery', 'layer', 'element', 'form'], function (exports) {
        var $ = layui.jquery
            , form = layui.form;
            
        //SWUI基本原型函数
        var SWUIObject = function (moduleName) {
            this.v = '1.0.0';  //版本号
            this.MOD_NAME = moduleName;//模块名
            this.path = getPath;//js所在文件夹
            this.cssName = {
                THIS: 'swui-this',
                SHOW: 'layui-show', 
                HIDE: 'layui-hide'
            };
            this.winAttr = 'win-id',//窗口对应div属性名 
            this.isLock = false;
            this.data = [];
            this.options = {};
            this.configs = {};
            //配置
            this.config = function (options) {
                options = options || {};
                var opts = {}, settings = {};
                for (var key in options) {
                    if (key === 'options') {
                        opts = options[key];
                    }
                    else if (key === 'settings') {
                        settings = options[key];
                    }
                    else this.configs[key] = options[key];
                }
                for (var key in opts) {
                    this.options[key] = opts[key];
                }
                for (var key in settings) {
                    this.settings[key] = settings[key];
                }
                return this;
            };
            //初始化
            this.init = function (options, callback) {
                if (this.Utils.isObject(options)) {
                    this.config(options);
                } else if (this.Utils.isFunction(options)) {
                    callback = options;
                }
                if (this.Utils.isFunction(this.render))
                    this.render.call(this, callback);
            };
            //设置数据
            this.setData = function (options, callback) {
                var util = this.Utils;
                if (!options.urlcode)
                    return;
                var data,url=swui.setter.getUrl(options.urlcode);
                var params = {
                    async: (options.async==null || options.async=="") ? true : options.async,
                    dataType: options.dataType || 'json',
                    loadmsg: '',
                    beforeSend: function(XMLHttpRequest){
                                if (util.isFunction(options.beforeSend)) 
                                    return options.beforeSend.call(XMLHttpRequest);
                                else return true;
                            }
                }
                ajax.get(url,options.data,params,function (res) {
                    res = res.data;
                    if (typeof res === "string") {
                        data = JSON.parse(res);
                        if (util.isFunction(callback))
                            callback.call(this, data);
                    } else if (typeof (res) == "object" && (Object.prototype.toString.call(res).toLowerCase() == "[object object]" || Object.prototype.toString.call(res).toLowerCase() == "[object array]")) {
                        data = res;
                        if (util.isFunction(callback))
                            callback.call(this, data);
                    } else {
                        layer.msg('请对接口返回json对象或者json字符串', {
                            offset: '40px',
                            zIndex: 999999999
                        });
                    }
                }, function (e) {
                    if (e.status != 200) {
                        layer.msg(e.statusText);
                    } else {
                        layer.msg('请对接口返回json对象或者json字符串', {
                            offset: '40px',
                            zIndex: 999999999
                        });
                    }
                });
            };
            //辅助方法
            this.Utils = {
                isUndefined: function (obj) {
                    return typeof obj === 'undefined';
                },
                isBoolean: function (obj) {
                    return typeof obj === 'boolean';
                },
                isString: function (obj) {
                    return typeof obj === 'string';
                },
                isNumber: function (obj) {
                    return typeof obj === 'number';
                },
                isObject: function (obj) {
                    return typeof obj == 'object';
                },
                isArray: function (o) {
                    return Object.prototype.toString.call(o) == '[object Array]';
                },
                isFunction: function (func) {
                    return func && Object.prototype.toString.call(func) === '[object Function]';
                },
                isDom: function (obj) {
                    return !!(obj && typeof window !== 'undefined' && (obj === window || obj.nodeType));
                }, 
                indexOfObjectInArray: function (key, obj, arr) {
                    var index = -1;
                    for (var i=0;i<arr.length;i++) {
                        if (arr[i][key] === obj[key]) {
                            index = i;
                            break;
                        }
                    }
                    return index;
                },
                guid: function () {//生成GUID
                    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
                        var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
                        return v.toString(16);
                    });
                },
                rndNum: function (n) {//生成随机长度的数
                    var rnd = "";
                    for (var i = 0; i < n; i++)
                        rnd += Math.floor(Math.random() * 10);
                    return rnd;
                }
            };
            //表单验证
            this.verify = {
                required: [
                    /[\S]+/
                    , '必填项不能为空'
                ]
                , phone: [
                    /^1\d{10}$/
                    , '请输入正确的手机号'
                ]
                , email: [
                    /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/
                    , '邮箱格式不正确'
                ]
                , url: [
                    /(^#)|(^http(s*):\/\/[^\s]+\.[^\s]+)/
                    , '链接格式不正确'
                ]
                , number: [
                    /^\d+$/
                    , '只能填写数字'
                ]
                , date: [
                    /^(\d{4})[-\/](\d{1}|0\d{1}|1[0-2])([-\/](\d{1}|0\d{1}|[1-2][0-9]|3[0-1]))*$/
                    , '日期格式不正确'
                ]
                , identity: [
                    /(^\d{15}$)|(^\d{17}(x|X|\d)$)/
                    , '请输入正确的身份证号'
                ]
            };
            //获取swui设置
            this.getSetting = function (settingKey) {
                return this.settings[settingKey];
            };
            //icon图标
            this.getIconHtml = function (icon, height) {
                if (!icon) return '';
                else if (icon.indexOf('<fa>')===0) {//以<fa>开头表示font-awesome图标
                    return '<i class="fa ' + icon.substr(4) + ' fa-fw"></i>';
                }
                else if (icon.indexOf('<layui>')===0) {//以<layui>开头表示layui图标
                    return '<i class="layui-icon ' + icon.substr(7) + '"></i>';
                }
                else {//默认为图片的路径
                    if (height) return '<img src="' + icon + '" height="'+height+'px" />';
                    return '<img src="' + icon + '" />';
                }
            };
            //绑定事件
            this.on = function (eventname, callback) {
                if (!this.Utils.isFunction(callback)) return;
                this.event[eventname] = callback;
            };
            //阻止事件冒泡
            this.sp = function (event) {
                layui.stope(event);
            };
            //重置元素的事件
            this.resetEvent = function(event, selector, func, elem, selfonly) {
                if (!this.Utils.isFunction(func)) return;
                var othis = this;
                var fun = function (e) {
                    if (layui.data('swui','lockscreen') === true) return false;
                    !e && (e = window.event);
                    if (selfonly && !$(e.target||e.srcElement).is(this)) {
                        othis.sp(e);
                        return false;
                    }
                    func.call(this, e);
                }
                if (elem) $(elem).off(event, selector).on(event, selector, fun);
                else $(selector).off(event).on(event, fun);
            };
            //为dom添加swui-this类
            this.selectDom = function (selector) {
                $(selector).addClass(this.cssName.THIS).siblings().removeClass(this.cssName.THIS);
            };
            //为dom添加layui-show类
            this.showDom = function (selector) {
                $(selector).addClass(this.cssName.SHOW).siblings().removeClass(this.cssName.SHOW);
            };
            this.ContextMenu = function (target, items, cls, position) {
                if (!items || items.length === 0) return;
                var othis = this;
                var args = [].slice.call(arguments,4);
                var style = '',over = false;
                for(var property in position){
                    if (property === 'over') {
                        over = position[property];//false为尽量不遮住任务栏，true为可以遮挡(即不考虑任务栏的宽和高)
                        continue;
                    }
                    style+=property+':'+position[property]+';';
                }
                //右键点击
                var div = '<ul class="' + cls + '" style="' + style + '">';
                $(items).each(function (index, item) {
                    div += '<li'+function(){
                        var s = ' ';
                        if (item.disablewhen) {
                            switch (item.disablewhen.key) {
                                case 'status':
                                    if (swui.getWindowStatus($(target).closest('li').attr(othis.winAttr)) === item.disablewhen.value)
                                        s += 'disabled="disabled"';
                                    break;
                                default: break;
                            }
                        }
                        else if (item.childrens) {
                            s += 'class="parentmenu"';
                        }
                        else if (item.space) {//分隔符
                            s += 'class="separator"';
                        }
                        return s;
                    }()+'>' + function(){
                        if (item.name) {
                            var tick = false;
                            if (item.tickwhen) {//右键选项值有两种情况，在相应情况下打勾
                                var v = swui.getSetting(item.tickwhen.key) || false;
                                if (v === item.tickwhen.value)
                                    return '<i class="layui-icon layui-icon-ok"></i>' + item.name;
                                else return item.name;
                            }
                            else if (item.childrens && item.childrens.length > 0) {//存在子项,暂时只支持一级
                                var s = othis.getIconHtml(item.icon) + item.name + '<i class="layui-icon layui-icon-right"></i>';
                                s += '<ul class="'+othis.cssName.HIDE+'">';
                                $(item.childrens).each(function(index, item){
                                    if (item.space) {//分隔符
                                        s += '<li class="separator"></li>';
                                    }
                                    else s+='<li>'+item.name+'</li>';
                                });
                                s += '</ul>';
                                return s;
                            }
                            else //右键选项值不变情况下
                                return othis.getIconHtml(item.icon) + item.name;
                        }
                        else if (item.setkey) {//右键选项值有多种情况，在相应情况下变换内容
                            var v = swui.getSetting(item.setkey) || false;
                            for(var i=0;i<item.values.length;i++) {
                                if (v === item.values[i].value) {
                                    return othis.getIconHtml(item.values[i].icon) + item.values[i].name;
                                }
                            }
                        }
                        else return '';
                    }() + '</li>';
                });
                div += '</ul>';
                //移除之前任务项右键菜单
                $('.'+cls).remove();
                //渲染当前任务项右键菜单
                div = $(div).appendTo($(document.body));
                //位置调整(不超出界面)
                var winWidth = swui.elems.body.width(),
                    winHeight = swui.elems.body.height(),
                    width = div.outerWidth(),
                    height = div.outerHeight(),
                    left = div.offset().left,
                    top = div.offset().top,s={},t=0,b=0,l=0,r=0;
                //自动隐藏任务栏并且触发点不是任务栏，可以遮住任务栏位置
                if (swui.getSetting('taskbarHide') && $(target).closest('.swui-taskbar').length === 0)
                    over = true;
                if (!over) {//尽量不遮住任务栏
                    switch (swui.getSetting('taskbarMode')) {
                        case 'left':
                            l=swui.taskbar.taskbarWidth;
                            break;
                        case 'right':
                            r=swui.taskbar.taskbarWidth;
                            break;
                        case 'top':
                            t=swui.taskbar.taskbarHeight;
                            break;
                        case 'bottom':
                        default:
                            b=swui.taskbar.taskbarHeight;
                            break;
                    }
                }
                if (height > winHeight - t - b) {
                    if (height > winHeight) s.height = winHeight;
                    if (t === 0) s.top = 0;
                    else {
                        s.top = '';
                        s.bottom = 0;
                    }
                }
                else if (top + height > winHeight - b) {
                    if (height < top - t) s.top = top - height;
                    else if (b > 0) {
                        s.top = '';
                        s.bottom = b;
                    }
                    else s.top = t;
                }
                if (left < l) s.left = l;
                else if (left + width > winWidth - r) {
                    if (r > 0) {
                        s.left = '';
                        s.right = r;
                    }
                    else s.left = winWidth - width;
                }
                div.css(s);
                //绑定单击回调函数
                othis.resetEvent('click', 'ul.'+cls+' li:not(.separator)', function (){
                    var index = $(this).index();
                    if (!$(this).parent().hasClass(cls)) {//子项
                        var ind = $(this).parent().parent().index();
                        var item = items[ind].childrens[index];
                        if (!othis.Utils.isFunction(item.handler))
                            return;
                        //调用回调函数
                        item.handler.call(this, args, item);
                    }
                    else if (items[index].name) {
                        if (!othis.Utils.isFunction(items[index].handler))
                            return;
                        //调用回调函数
                        items[index].handler.call(this, args, items[index]);
                    }
                    else if (items[index].setkey) {//可变换文字及事件的右键功能项
                        var v = swui.getSetting(items[index].setkey);
                        for(var i=0;i<items[index].values.length;i++) {
                            if ((!v && !items[index].values[i].value) || v === items[index].values[i].value) {
                                if (!othis.Utils.isFunction(items[index].values[i].handler))
                                    return;
                                //调用回调函数
                                items[index].values[i].handler.call(this, args, items[index].values[i]);
                                break;
                            }
                        }
                    }
                    div.remove();
                });
                //阻止右键菜单冒泡
                $('ul.'+cls+' li').on('click mousedown', othis.sp);
                othis.resetEvent('mouseenter', 'ul.'+cls+' li.parentmenu', function (){
                    var ul = $(this).children('ul');
                    ul.removeClass(othis.cssName.HIDE).removeClass('left');;
                    if (ul.width()+ul.offset().left>winWidth)
                        ul.addClass('left');
                });
                othis.resetEvent('mouseleave', 'ul.'+cls+' li.parentmenu', function (){
                    $(this).children('ul').addClass(othis.cssName.HIDE);
                });
            }
        };

        //构造函数
        var SWUI = function () {
            SWUIObject.call(this, 'swui');
            this.baseObject = SWUIObject;
            this.settings = layui.data('swui').settings || {
                color: 31,
                customColors: [],
                taskbarMode: 'bottom',
                bgSrc: 'images/bg_01.jpg',//'auto'设置为自动轮播
                lockBgSrc: 'images/bg_01.jpg',//'auto'设置为自动轮播
                audioSrc: this.path + 'audio/236',
                startSize: 'sm'
            };
            this.bgImages = ['images/bg_01.jpg','images/bg_02.jpg','images/bg_03.jpg','images/bg_04.jpg','images/bg_05.jpg'];
            this.elems = {};
            this.event = {};    //自定义事件
            this.lastActionTime;//记录最后鼠标移动或点击、按下键盘的时间
        }

        //原型
        SWUI.prototype = {
            //初始化html元素及事件
            render: function (callback) {
                var othis = this;
                var configs = othis.configs,
                    settings = othis.settings;
                othis.renderElems(configs.elem);
                othis.renderTitle();
                //播放声音
                if (configs.audioPlay && !layui.sessionData('swuiSession').audio) {
                    var audio = document.createElement("audio"), format = undefined;
                    audio.onended = function () {
                        audio = null;
                    }
                    if (audio.canPlayType("audio/mp3"))
                        format = '.mp3';
                    else if (audio.canPlayType("audio/ogg"))
                        format = ".wav";
                    if (format) {
                        audio.src = settings.audioSrc + format;
                        audio.play();
                        //播放过后 刷新页面不再播放
                        layui.sessionData('swuiSession', { key: 'audio', value: true });
                    }
                }
                //背景图渲染
                if (configs.renderBg) {
                    othis.renderBg();
                }
                //配置各模块
                var i = 0;
                var loadend = function(arg){
                    i++;
                    if (i === 6) {
                        var ooo = {bgColor:'rgba(0,0,0,0.6)',border:false,width:80,height:30};
                        var msg = '<p style="line-height:30px;color:#fff;text-align:center;">桌面加载完毕</p>';
                        layxwin.msg(msg,ooo);
                    }
                }
                if (othis.desktop && configs['desktop']) {
                    othis.desktop.init($.extend({elem:othis.elems.desktop,moveable:true}, configs.desktop),loadend);
                }
                if (othis.taskbar && configs['taskbar']) {
                    othis.taskbar.init($.extend({elem:[othis.elems.taskItems,othis.elems.taskIcons.find('ul')]}, configs.taskbar),loadend);
                }
                if (othis.menu && configs['menu']) {
                    othis.menu.init($.extend({elem:othis.elems.startMenu}, configs.menu),loadend);
                }
                if (othis.helper && configs['helper']) {
                    othis.helper.init($.extend({container:othis.elems.desktop[0],anima:true,close:true}, configs.helper),loadend);
                }
                if (othis.live2d && configs['live2d']) {
                    othis.live2d.init($.extend({container:othis.elems.desktop[0],anima:true}, configs.live2d),loadend);
                }
                if (othis.control && configs['control']) {
                    othis.control.init($.extend({elem:othis.elems.console}, configs.control),loadend);
                }
                //任务栏模式渲染
                othis.renderTaskbar();
                //开始菜单尺寸设置
                othis.renderStartSize();
                //颜色渲染
                othis.renderColor();
                //othis.removeCustomStyle('a1');
                othis.setUser();
                //任务栏右下角显示时间
                othis.sysTime(othis.elems.time, '<p>!HH:!mm:!ss</p><p>!yyyy-!M-!d</p>');
                //重置事件
                othis.resetEvents();
                //初始化完毕回调
                if (othis.Utils.isFunction(callback))
                    callback.call(this, othis);
            }

            //构建ui各部分主体html
            , renderElems: function(elem){
                if (elem) this.elems.body = $(elem);
                else this.elems.body = $(document.body);
                !this.elems.body.hasClass('swui-body') && this.elems.body.addClass('swui-body');
                if (swui.setter.name) this.elems.body.append('<div class="swui-name">'+swui.setter.name+'</div>');
                //五大区域
                this.elems.userMenu = $('<div class="swui-userinfo sp slideDown"></div>').prependTo(this.elems.body);//用户信息
                this.elems.console = $('<div class="swui-console sp layui-hide slideOutRight"></div>').prependTo(this.elems.body);//控制中心
                this.elems.startMenu = $('<div class="swui-start sp slideDown"></div>').prependTo(this.elems.body);//开始菜单
                this.elems.taskbar = $('<div class="swui-taskbar"></div>').prependTo(this.elems.body);//任务栏
                this.elems.desktop = $('<div class="swui-desktop"></div>').prependTo(this.elems.body);//桌面
                //任务栏按钮及任务项
                this.elems.startBtn = $('<div class="swui-taskbar-start sp">'+this.getIconHtml(swui.setter.logo)+'</div>').appendTo(this.elems.taskbar);//开始按钮
                this.elems.viewBtn = $('<div class="swui-taskbar-view sp" title="任务视图"><div></div></div>').appendTo(this.elems.taskbar);//任务视图
                this.elems.taskItems = $('<ul class="swui-taskbar-task"></ul>').appendTo(this.elems.taskbar);//任务项
                this.elems.taskIcons = $('<div class="swui-taskbar-icon swui-task-fixed sp"><i class="fa fa-angle-up"></i><ul class="'+this.cssName.HIDE+'"></ul></div>').appendTo(this.elems.taskbar);//显示隐藏的图标
                this.elems.user = $('<div class="swui-taskbar-user sp"></div>').appendTo(this.elems.taskbar);//用户信息图标
                this.elems.time = $('<div class="swui-taskbar-time"></div>').appendTo(this.elems.taskbar);//任务栏时间
                this.elems.consoleBtn = $('<div class="swui-taskbar-console sp"><i class="fa fa-comment-o"></i></div>').appendTo(this.elems.taskbar);//控制中心按钮
                this.elems.taskHide = $('<div class="swui-taskbar-desktop"></div>').appendTo(this.elems.taskbar);//显示桌面
            }

            //重置事件
            , resetEvents: function(){
                var othis = this;
                setInterval(function() {
                    if (userAction) {
                        userAction = false;
                    }
                }, 1000);
                //绑定桌面点击事件
                $(document).off('contextmenu').on('contextmenu', function () {//阻止原有的右键菜单
                    return false;
                }).off('mousemove keydown').on('mousemove keydown', function (e) {
                    if (!userAction) {
                        userAction = true;
                        othis.lastActionTime = new Date().getTime();
                    }
                }).off('click mousedown', '.sp').on('click mousedown', '.sp', function (e) {
                    othis.removeContextMenu();
                    othis.sp(e);//阻止冒泡
                }).on('mousedown', function (e) {
                    e = e||window.event;
                    var target = e.target||e.srcElement;
                    othis.removeContextMenu();//移除显示的任务项右键菜单和菜单项右键菜单
                    othis.hideStartMenu();//隐藏开始菜单
                    othis.hideUserMenu();//隐藏用户信息菜单
                    othis.hideTaskIcon();//隐藏任务小图标
                    othis.hideConsole();//隐藏控制中心
                    othis.removeFocus(target);//移除所有的选中状态
                }).off('keyup').on('keyup', function (e) {
                    //快捷键操作菜单
                    switch (e.keyCode) {
                        case 18://Alt键 开始菜单
                            othis.elems.startBtn.trigger('click');
                            break;
                        case 17://Ctrl键 控制中心菜单
                            othis.elems.consoleBtn.trigger('click');
                            break;
                        case 16://Shift键 用户信息菜单
                            othis.elems.user.trigger('click');
                            break;
                        case 27://Esc键 隐藏所有菜单
                            othis.removeContextMenu();
                            othis.hideStartMenu();
                            othis.hideUserMenu();
                            othis.hideTaskIcon();
                            othis.hideConsole();
                            break;
                    }
                }).on('mouseover', '*[data-help]', function () {
                    var helpinfo = $(this).data('help');
                    if (helpinfo) {
                        swui.helper.showMessage(helpinfo);
                        swui.live2d.showMessage(helpinfo);
                    }
                }).on('mouseout', '*[data-help]', function () {
                    swui.helper.hideMessage();
                    swui.live2d.hideMessage();
                });
                //绑定左下角开始点击事件
                othis.resetEvent('click', othis.elems.startBtn, function(){
                    othis.elems.startBtn.toggleClass(othis.cssName.THIS);
                    othis.elems.startMenu.toggleClass('slideUp').toggleClass('slideDown');
                    if (othis.elems.body.hasClass('taskHide')) 
                        othis.elems.body.removeClass('taskHide').addClass('taskShow');
                });
                //绑定任务视图点击事件
                othis.resetEvent('click', othis.elems.viewBtn, function(){
                    othis.elems.viewBtn.toggleClass(othis.cssName.THIS);
                    layer.msg('展开任务视图');
                });
                //绑定显示隐藏图标按钮点击事件
                othis.resetEvent('click', othis.elems.taskIcons, function(){
                    othis.elems.taskIcons.toggleClass(othis.cssName.THIS);
                    othis.elems.taskIcons.find('ul').toggleClass(othis.cssName.HIDE).toggleClass(othis.cssName.SHOW);
                });
                //绑定用户信息按钮点击事件
                othis.resetEvent('click', othis.elems.user, function(){
                    othis.elems.user.toggleClass(othis.cssName.THIS);
                    othis.elems.userMenu.toggleClass('slideUp').toggleClass('slideDown');
                    if (othis.elems.body.hasClass('taskHide')) 
                        othis.elems.body.removeClass('taskHide').addClass('taskShow');
                });
                //绑定右下角控制中心点击事件
                othis.resetEvent('click', othis.elems.consoleBtn, function(){
                    othis.elems.consoleBtn.toggleClass(othis.cssName.THIS);
                    othis.elems.console.removeClass(othis.cssName.HIDE).toggleClass('slideInRight').toggleClass('slideOutRight');
                });
                //绑定右下角显示桌面点击事件
                othis.resetEvent('click', othis.elems.taskHide, function () {
                    //最小化或还原所有窗体
                    layxwin.minAll();
                });
                //窗体大小自适应
                othis.resetEvent('resize', window, function(e){
                    if (swui.taskbar && swui.taskbar.resizeEvent)
                        swui.taskbar.resizeEvent(e);
                    if (swui.desktop && swui.desktop.resizeEvent)
                        swui.desktop.resizeEvent(e);
                    if (swui.helper && swui.helper.resizeEvent)
                        swui.helper.resizeEvent(e);
                    if (swui.live2d && swui.live2d.resizeEvent)
                        swui.live2d.resizeEvent(e);
                });
            }
            , renderTitle: function (){
                document.title = swui.setter.name;
            }

            //重置主题色
            , resetColor: function (color) {
                if (color) {
                    this.settings.color = color;
                    //缓存数据
                    layui.data('swui', { key: 'settings', value: this.settings });
                }
                this.renderColor();
                //重置所有iframe的颜色
                for (var i = 0; i < window.frames.length; i++) {
                    if (window.frames[i].swui) {
                        window.frames[i].swui.settings.color = color;
                        window.frames[i].swui.renderColor();
                    }
                }
            }
            //渲染主题色
            , renderColor: function (colorStyle) {
                if (colorStyle) {
                    //注册自定义主题色
                    if (!this.setCustomStyle(colorStyle)) {
                        layer.msg('自定义主题色的参数错误');
                        return null;
                    }
                }
                if (this.settings.color) {
                    if (!colorStyle && isNaN(parseInt(this.settings.color)))//自定义主题
                        this.setCustomStyle({id:this.settings.color});
                    if (this.elems.body.attr('class')) {
                        this.elems.body.attr('class', this.elems.body.attr('class').replace(/\bswui-color.*?\b/g, '').replace(/(^\s*)|(\s*$)/g, ""));
                    }
                    this.elems.body.addClass('swui-color' + this.settings.color);
                }
                return this.settings.color;
            }
            //删除自定义主题色
            , removeColor: function (color) {
                var flag = false;
                for (var i=0;i<this.settings.customColors.length;i++) {
                    if (this.settings.customColors[i].id === color) {
                        this.settings.customColors.splice(i, 1);
                        flag = true;
                        break;
                    }
                }
                if (this.settings.color === color) {
                    this.resetColor(31);
                }
                else if (flag) {
                    layui.data('swui', { key: 'settings', value: this.settings });
                }
                return flag;
            }

            //重置任务栏模式
            , resetTaskbar: function (taskbarMode) {
                !taskbarMode && (taskbarMode = 'bottom');
                var fromMode = this.settings.taskbarMode;
                if (fromMode === taskbarMode)
                    return;
                this.settings.taskbarMode = taskbarMode;
                //缓存数据
                layui.data('swui', { key: 'settings', value: this.settings });
                this.renderTaskbar(fromMode);
            }
            //隐藏/显示任务栏
            ,setTaskBarHide: function (type) {
                switch (type) {
                    case 'set':
                        this.settings.taskbarHide = true;
                        this.elems.body.addClass('taskHide');
                        //重设窗口移动范围和最大化范围
                        var auto = this.elems.body.hasClass('taskHide') || this.elems.body.hasClass('taskShow');
                        layxwin.changeTaskbarMode(this.settings.taskbarMode, 'setHide', auto);
                        break;
                    case 'hide':
                        if (this.elems.body.hasClass('taskShow') && !this.elems.startBtn.hasClass(this.cssName.THIS) && !this.elems.user.hasClass(this.cssName.THIS) && this.elems.taskItems.children('.swui-task-menu').length === 0)
                            this.elems.body.removeClass('taskShow').addClass('taskHide');
                        break;
                    case 'show':
                        if (this.elems.body.hasClass('taskHide'))
                            this.elems.body.removeClass('taskHide').addClass('taskShow');
                        break;
                    default:
                        this.settings.taskbarHide = false;
                        this.elems.body.removeClass('taskShow taskHide');
                        var auto = this.elems.body.hasClass('taskHide') || this.elems.body.hasClass('taskShow');
                        layxwin.changeTaskbarMode(this.settings.taskbarMode, 'cancelHide', auto);
                        break;
                }
                layui.data('swui', { key: 'settings', value: this.settings });
            }
            //渲染任务栏模式
            , renderTaskbar: function (fromMode) {
                if (this.elems.body.attr('class')) {
                    this.elems.body.attr('class', this.elems.body.attr('class').replace(/\btaskbarIn.*?\b/g, '').replace(/(^\s*)|(\s*$)/g, ""));
                }
                var cls,iconCls,mode = this.settings.taskbarMode;
                switch (mode) {
                    case 'left':
                        cls = 'taskbarInLeft';
                        iconCls = 'fa fa-angle-right';
                        break;
                    case 'right':
                        cls = 'taskbarInRight';
                        iconCls = 'fa fa-angle-left';
                        break;
                    case 'top':
                        cls = 'taskbarInTop';
                        iconCls = 'fa fa-angle-down';
                        break;
                    case 'bottom':
                    default:
                        cls = 'taskbarInBottom';
                        iconCls = 'fa fa-angle-up';
                        break;
                }
                if (this.settings.taskbarHide === true) cls += ' taskHide';
                if (this.settings.taskViewHide === true) cls += ' noTaskView';
                this.elems.body.addClass(cls);
                this.elems.taskIcons.find("> i").removeClass().addClass(iconCls);
                swui.taskbar.changeMode(mode);//改变任务栏依靠位置
                var auto = this.elems.body.hasClass('taskHide') || this.elems.body.hasClass('taskShow');
                layxwin.changeTaskbarMode(mode, fromMode, auto);//改变窗口弹出位置
            }
            //隐藏/显示任务视图按钮
            ,setTaskViewHide: function (hide) {
                this.settings.taskViewHide = hide;
                layui.data('swui', { key: 'settings', value: this.settings });
                if (hide) swui.elems.body.addClass('noTaskView');
                else swui.elems.body.removeClass('noTaskView');
            }

            //重置开始菜单尺寸
            , resetStartSize: function (startSize) {
                if (startSize) {
                    if (this.settings.startSize === startSize)
                        return;
                    this.settings.startSize = startSize;
                    //缓存数据
                    layui.data('swui', { key: 'settings', value: this.settings });

                    $('.preview-start').removeClass('xs sm lg');
                    $('.preview-start').addClass(startSize);
                }
                this.renderStartSize();
            }
            //渲染开始菜单尺寸
            , renderStartSize: function () {
                swui.menu.changeSize(this.settings.startSize);
            }

            //重置背景图
            , resetBg: function (bgSrc) {
                if (bgSrc) {
                    this.settings.bgSrc = bgSrc;
                    //缓存数据
                    layui.data('swui', { key: 'settings', value: this.settings });
                }
                this.renderBg();
            }
            //渲染背景图
            , renderBg: function () {
                var bgSrc = this.settings.bgSrc;
                if (bgSrc)
                    this.elems.body.css('background-image', 'url(' + bgSrc + ')');
            }
            //取得指定或随机的背景图
            , setBgImage: function (obj, src) {
                var p;
                if (this.Utils.isString(src))
                    p = src;
                else if (this.Utils.isNumber(src) && src >= 0 && src < this.bgImages.length)
                    p = this.bgImages[src];
                else {
                    var ind = Math.floor(Math.random()*this.bgImages.length);
                    p = this.bgImages[ind];
                }
                $(obj).css('background-image', 'url('+p+')');
            }
            //重置锁屏图
            , resetLockBg: function (bgSrc) {
                if (bgSrc) {
                    this.settings.lockBgSrc = bgSrc;
                    //缓存数据
                    layui.data('swui', { key: 'settings', value: this.settings });
                }
            }

            //全屏
            , fullScreen: function (element) {
                // 判断各种浏览器，找到正确的方法
                var requestMethod = element.requestFullScreen || //W3C
                    element.webkitRequestFullScreen || //Chrome等
                    element.mozRequestFullScreen || //FireFox
                    element.msRequestFullScreen; //IE11
                if (requestMethod) {
                    requestMethod.call(element);
                }
                else if (typeof window.ActiveXObject !== "undefined") {//for Internet Explorer
                    var wscript = new ActiveXObject("WScript.Shell");
                    if (wscript !== null) {
                        wscript.SendKeys("{F11}");
                    }
                }
            }

            //退出全屏
            , exitFullScreen: function () {
                // 判断各种浏览器，找到正确的方法
                var exitMethod = document.exitFullscreen || //W3C
                    document.mozCancelFullScreen ||    //Chrome等
                    document.webkitExitFullscreen || //FireFox
                    document.webkitExitFullscreen; //IE11
                if (exitMethod) {
                    exitMethod.call(document);
                }
                else if (typeof window.ActiveXObject !== "undefined") {//for Internet Explorer
                    var wscript = new ActiveXObject("WScript.Shell");
                    if (wscript !== null) {
                        wscript.SendKeys("{F11}");
                    }
                }
            }

            //隐藏开始菜单
            , hideStartMenu: function () {
                this.elems.startMenu.removeClass('slideUp').addClass('slideDown');//隐藏开始菜单
                this.elems.startBtn.removeClass(this.cssName.THIS);
                //if (this.elems.body.hasClass('taskShow'))//此处会导致点击不了任务项
                //    this.elems.body.removeClass('taskShow').addClass('taskHide');
            }

            //隐藏用户信息菜单
            , hideUserMenu: function () {
                this.elems.userMenu.removeClass('slideUp').addClass('slideDown');//隐藏用户信息菜单
                this.elems.user.removeClass(this.cssName.THIS);
            }

            //隐藏任务小图标
            , hideTaskIcon: function () {
                this.elems.taskIcons.find('ul').removeClass(this.cssName.SHOW).addClass(this.cssName.HIDE);
                this.elems.taskIcons.removeClass(this.cssName.THIS);
            }

            //隐藏控制中心
            , hideConsole: function () {
                this.elems.console.removeClass('slideInRight').addClass('slideOutRight');//隐藏控制中心
                this.elems.consoleBtn.removeClass(this.cssName.THIS);
            }

            , removeFocus: function (target) {
                this.elems.startBtn.removeClass(this.cssName.THIS);//移除开始菜单按钮的选中样式
                this.elems.viewBtn.removeClass(this.cssName.THIS);//移除任务视图按钮的选中样式
                this.elems.consoleBtn.removeClass(this.cssName.THIS);//移除控制中心按钮的选中样式
                //this.elems.taskItems.children('> li.'+this.cssName.THIS).removeClass(this.cssName.THIS);//移除任务栏选中状态
                this.elems.desktop.children('.swui-desktop-item.'+this.cssName.THIS).removeClass(this.cssName.THIS);//移除桌面app选中状态
                this.elems.taskItems.children('li.swui-task-menu').removeClass('swui-task-menu');//移除任务右键选中状态
                if (!$(target).closest('li').is('.swui-taskitems-on')) {
                    if ($(target).closest('ul').parent().is('.swui-taskitems-on'))
                        this.elems.taskItems.children('li.swui-taskitems-on').removeClass('swui-taskitems-on');//点击任务项时先不隐藏预览层，等触发点击事件后再隐藏
                    else this.elems.taskItems.children('li.swui-taskitems-on').removeClass('swui-taskitems-on').children('ul').hide();//移除预览层锁定状态并隐藏
                }
            }

            //验证表单
            , verifyForm: function (button) {
                var button = $(button),
                    stop = null,
                    device = layui.device(),
                    DANGER = 'layui-form-danger',
                    elem = button.parents('.layui-form'),
                    verifyElem = elem.find('*[win-verify]'),//获取需要校验的元素
                    that = this,
                    windowfunc = this.window;
                layui.each(verifyElem, function (index, item) {
                    var othis = $(this), ver = othis.attr('win-verify').split('|');
                    var tips = '', value = othis.val();
                    othis.removeClass(DANGER);
                    layui.each(ver, function (_, thisVer) {
                        var isFn = that.Utils.isFunction(that.verify[thisVer]);
                        if (that.verify[thisVer] && (isFn ? tips = that.verify[thisVer](value, item) : !that.verify[thisVer][0].test(value))) {
                            windowfunc.msg(tips || that.verify[thisVer][1], {
                                icon: 5
                                , shift: 6
                            });
                            //非移动设备自动定位焦点
                            if (!device.android && !device.ios) {
                                item.focus();
                            }
                            othis.addClass(DANGER);
                            return stop = true;
                        }
                    });
                    if (stop) return stop;
                });
                return !stop;
            }
            , setUser: function () {
                var user = layui.data('swui','user');
                if (!user) return;
                this.elems.user.attr('title',user.NickName).css({backgroundImage:'url('+user.ImagePath+')'});
                var html = '<div class="left"><img src="'+user.ImagePath+'" /></div>';
                html += '<div class="right"><div>'+user.NickName+'</div><div>'+user.Remark+'</div></div>';
                html += '<div class="middle">上次登录时间：2019-04-24 11:23:30<br/>本次登录时间：2019-04-24 13:23:30</div>';
                //html += '<div class="layui-btn layui-btn-sm">消息<span class="layui-badge layui-bg-gray">1</span></div><div class="layui-btn layui-btn-sm">动态<span class="layui-badge-dot layui-bg-orange"></span></div>';
                html += '<div class="bottom"><div class="layui-btn layui-btn-primary layui-btn-radius">用户信息</div><div class="layui-btn layui-btn-normal layui-btn-radius">退出系统</div></div>';
                this.elems.userMenu.append(html);
            }, setMessageCount: function () {//提取未读消息总数
                var user = layui.data('swui','user');
                if (!user) return;
                var othis = this;
                ajax.get(swui.setter.getUrl('countmsg'),{UserCode:user.UserCode},null,function(result){
                    if (result.Code === 200) {
                        var dot = othis.elems.user.children('.layui-badge-dot');
                        var bdg = othis.elems.userMenu.find('.left .layui-badge');
                        if (result.Data > 0) {
                            if (dot.length === 0)
                                othis.elems.user.append('<span class="layui-badge-dot swui-badge"></span>');
                            if (bdg.length === 0)
                                othis.elems.userMenu.children('.left').append('<span class="layui-badge swui-badge">'+result.Data+'</span>');
                        }
                        else {
                            if (dot.length > 0) dot.remove();
                            if (bdg.length > 0) bdg.remove();
                        }
                    }
                });
            }
            //显示系统时间
            , sysTime: function (selector, formatStr) {
                var setting = this.settings;
                return setInterval(function () {
                    //获取系统时间。
                    var dateTime = new Date();
                    
                    var str = formatStr;
                    var mode = setting.taskbarMode;
                    if (mode === 'left' || mode === 'right')
                        str = '<p>!HH:!mm</p><p>!M-!d</p>';
                    var Week = ['日', '一', '二', '三', '四', '五', '六'];

                    if (str != undefined) {
                        str = str.replace(/!yyyy|!YYYY/, dateTime.getFullYear());
                        str = str.replace(/!yy|!YY/, (dateTime.getYear() % 100) > 9 ? (dateTime.getYear() % 100).toString() : '0' + (dateTime.getYear() % 100));
                        str = str.replace(/!MM/, (dateTime.getMonth() + 1) > 9 ? (dateTime.getMonth() + 1).toString() : '0' + (dateTime.getMonth() + 1));
                        str = str.replace(/!M/g, (dateTime.getMonth() + 1));

                        str = str.replace(/!w|!W/g, Week[dateTime.getDay()]);

                        str = str.replace(/!dd|!DD/, dateTime.getDate() > 9 ? dateTime.getDate().toString() : '0' + dateTime.getDate());
                        str = str.replace(/!d|!D/g, dateTime.getDate());

                        str = str.replace(/!hh|!HH/, dateTime.getHours() > 9 ? dateTime.getHours().toString() : '0' + dateTime.getHours());
                        str = str.replace(/!h|!H/g, dateTime.getHours());
                        str = str.replace(/!mm/, dateTime.getMinutes() > 9 ? dateTime.getMinutes().toString() : '0' + dateTime.getMinutes());
                        str = str.replace(/!m/g, dateTime.getMinutes());

                        str = str.replace(/!ss|!SS/, dateTime.getSeconds() > 9 ? dateTime.getSeconds().toString() : '0' + dateTime.getSeconds());
                        str = str.replace(/!s|!S/g, dateTime.getSeconds());
                    } else {
                        var year = dateTime.getFullYear();
                        var month = dateTime.getMonth() + 1;
                        var day = dateTime.getDate();
                        var hh = dateTime.getHours();
                        var mm = dateTime.getMinutes();
                        var ss = dateTime.getSeconds();

                        //分秒时间是一位数字，在数字前补0。
                        mm = mm < 10 ? ("0" + mm) : mm;
                        ss = ss < 10 ? ("0" + ss) : ss;
                        str = year + '-' + month + '-' + day + ' ' + hh + ':' + mm + ':' + ss;
                    }

                    //将时间显示到指定的位置，时间格式形如：19:18:02
                    $(selector).html(str);
                }, 1000);
            }

            //停止显示时间
            , stopSysTime: function (obj) {
                window.clearInterval(obj);
            }
            //登录系统
            , login: function (option) {
                var othis = this;
                ajax.post(swui.setter.getUrl('login'),{UserName: option.username, Password: option.password},{header:false,loadmsg:'登录中...'},function (result) {
                    if (result.Code === 200) {
                        if (othis.Utils.isFunction(option.success))
                            option.success.call(othis, result);
                        else if (othis.Utils.isString(option.success)) {
                            switch (option.success) {
                                case 'login':
                                    layui.data('swui', {key:'user',value:result.Data});
                                    window.location.href = swui.setter.Page.home;
                                    break;
                                default:
                                    break;
                            }
                        }
                    } else {
                        if (othis.Utils.isFunction(option.error))
                            option.error.call(othis, result);
                        else if (othis.Utils.isString(option.error))
                            layer.msg(option.error);
                        else layer.msg(result.Message);
                    }
                })
            }
            , isOnline: function () {
                var flag = false;
                var session = layui.data('swui', 'session');
                if (!session||!session.Token||!session.ActionKey)
                    return false;
                ajax.syncPost(swui.setter.getUrl('isOnline'),null,null, function (result) {
                    if (result.Code === 200) {
                        flag = true;
                    } else {
                        layer.msg(result.Message);
                    }
                });
                return flag;
            }
            //锁屏
            , lockScreen: function (callback) {
                var self = this;
                ajax.html(swui.path + swui.setter.Page.lock, {}, {}, function (content) {
                    self.elems.locks = $(content).appendTo(self.elems.body);
                    self.setBgImage(self.elems.locks.filter('div'), self.settings.lockBgSrc);
                    layui.data('swui',{lockscreen:true});
                    var index,timer;
                    var ind = setInterval(function(){
                        self.setBgImage(self.elems.locks.filter('div'));
                    },60000);
                    var showUnlockDiv = function () {
                        swui.stopSysTime(index);
                        timer = setTimeout(function(){//30秒不登录则显示时间
                            showTimeDiv();
                        }, 30000);
                        $('#date_time').addClass(self.cssName.HIDE);
                        $('#login_div').removeClass(self.cssName.HIDE);
                        //解绑旧的鼠标键盘事件
                        $(document).off('mouseup');
                        $(document).off('keydown').on('keydown', function (e) {
                            var ev = document.all ? window.event : e;
                            if (ev.keyCode == 27) {
                                //按下ESC
                                showTimeDiv();
                            }
                        });
                    }, showTimeDiv = function () {
                        clearTimeout(timer);
                        index = swui.sysTime('#date_time', '<p id="time">!HH:!mm</p><p id="date">!M月!d日,星期!w</p>');
                        $('#date_time').removeClass(self.cssName.HIDE);
                        $('#login_div').addClass(self.cssName.HIDE);
                        //绑定新事件
                        $(document).on('mouseup', function (e) {
                            if (!e) e = window.event;
                            if (e.button == 0) {
                                //左键
                                showUnlockDiv();
                            }
                        });
                        $(document).off('keydown').on('keydown', function (e) {
                            var ev = document.all ? window.event : e;
                            if (ev.keyCode == 13) {
                                //按下回车
                                showUnlockDiv();
                            }
                        });
                    };
                    showTimeDiv();
                    $('#login_div >div:last').off('click').on('click', function(e){
                        layui.data('swui',{lockscreen:false});
                        self.logout();
                    });
                    //解锁点击
                    form.on('submit(unlock)', function (data) {
                        self.login({
                            username:'admin', 
                            password:data.field.password,
                            success: function(result) {
                                clearInterval(ind);
                                self.elems.locks.remove();
                                layui.data('swui',{lockscreen:false});
                            },
                            error: function(result) {
                                layer.msg('密码错误', { zIndex: 40000001 });
                            }
                        });
                        return false;
                    });
                });
            }
            //退出系统
            , logout: function () {
                ajax.post(swui.setter.getUrl('logout'),null,null, function (result) {
                    if (result.Code === 200) {
                        layer.alert('退出系统成功', {icon: 1,zIndex:999999999}, function(index){
                            layer.close(index);
                            layui.data('swui', {key:'session',remove:true});
                            window.location.href = swui.setter.Page.login;
                        });
                    } else {
                        layer.msg(result.Message);
                    }
                });
            }
            ,removeContextMenu: function(){
                $('.task-contextmenu,.menu-contextmenu,.app-contextmenu').remove();    //移除显示的任务项右键菜单和菜单项右键菜单
            }
            ,tabInit: function (selector) {
                var that = this;
                //Tab单击事件
                that.resetEvent('click', '.swui-tab-nav li', function () {
                    var othis = $(this),
                        index = index || othis.index(),
                        parents = othis.parents('.swui-tab').eq(0),
                        item = parents.find('.swui-tab-content').children('.swui-tab-item'),
                        filter = parents.attr('lay-filter');
                    that.selectDom(this);
                    that.showDom(item.eq(index));
                    //调用tabchange事件
                    layui.event.call(othis[0], that.MOD_NAME, 'tabchange(' + filter + ')', { index: index, elem: parents });
                }, selector);
            }
            ,tabOn: function (events, callback) {
                return layui.onevent.call(this, that.MOD_NAME, events, callback);
            }
            ,setCustomStyle: function (cs) {
                if (!cs.id && (!cs.style || !cs.color))
                    return false;
                if (!cs.id) {
                    var items=this.settings.customColors;
                    var id = items.length > 0 ? parseInt(items[items.length-1].id.substr(1)) : 0;
                    cs.id = "a" + (id+1);
                    this.settings.customColors.push(cs);
                    this.settings.color = cs.id;
                    layui.data('swui', { key: 'settings', value: this.settings });
                }
                else {
                    if (isNaN(parseInt(cs.id.substr(1))))//id命名不规范
                        return false;
                    var index = this.Utils.indexOfObjectInArray('id',cs,this.settings.customColors);
                    if (index === -1) {
                        if (!cs.style || !cs.color) return false;
                        this.settings.customColors.push(cs);
                        this.settings.color = cs.id;
                        layui.data('swui', { key: 'settings', value: this.settings });
                    }
                    else {
                        var change = false;
                        if (!cs.style) 
                            cs.style = this.settings.customColors[index].style;
                        else if (cs.style != this.settings.customColors[index].style) {
                            this.settings.customColors[index].style=cs.style; 
                            change = true;
                        }
                        if (!cs.color) 
                            cs.color = this.settings.customColors[index].color;
                        else if (cs.color != this.settings.customColors[index].color) {
                            this.settings.customColors[index].color=cs.color; 
                            change = true;
                        }
                        if (!cs.title) 
                            cs.title = this.settings.customColors[index].title;
                        else if (cs.title != this.settings.customColors[index].title) {
                            this.settings.customColors[index].title=cs.title; 
                            change = true;
                        }
                        if (change) {
                            this.settings.color = cs.id;
                            layui.data('swui', { key: 'settings', value: this.settings });
                        }
                    }
                }
                var style = document.getElementById(cs.id);
                if (!style) {
                    style = document.createElement("style");
                    style.setAttribute("id", cs.id);
                    style.type = "text/css";
                    document.getElementsByTagName("HEAD").item(0).appendChild(style);
                }
                var s = '.swui-color'+cs.id+'{';
                for (var i=0;i<cs.style.length;i++) {
                    s+=cs.style[i].css+':'+cs.style[i].color+';';
                }
                s+='}';
                style.innerHTML = s;
                return true;
            }
            ,removeCustomStyle: function(id){
                var items = this.settings.customColors;
                for (var i=0;i<items.length;i++) {
                    if (items[i].id === id) {
                        items.splice(i,1);
                        break;
                    }
                }
            }
            ,getWindowStatus: function(winid) {
                return layxwin.getWindow(winid).status;
            }
            ,setFocusWindow: function(preWinId) {
                var THIS = this.cssName.THIS;
                var winform = layxwin.getFocusWindow();
                if (!winform) {
                    var preWin = layxwin.getWindow(preWinId);
                    if (preWin) {
                        $(preWin.relateElem).removeClass(THIS).parent().closest('li').removeClass(THIS);
                    }
                    else {
                        this.elems.taskItems.find('>li >ul >li.'+THIS).removeClass(THIS);
                        this.elems.taskItems.children('li').removeClass(THIS);
                    }
                }
                else {
                    if (!winform.relateElem) return;
                    var $ul = $(winform.relateElem).parent();
                    if ($ul.parent().is('div.swui-taskbar-icon')) {
                        this.elems.taskItems.find('>li >ul >li.'+THIS).removeClass(THIS);
                        this.elems.taskItems.find('>li.'+THIS).removeClass(THIS);
                        return;
                    }
                    var $li = $ul.closest('li');
                    if ($li.length === 0) return;
                    this.elems.taskItems.find('>li >ul >li.'+THIS).removeClass(THIS);
                    $(winform.relateElem).addClass(THIS);
                    $li.addClass(THIS).siblings().removeClass(THIS);
                    var pos = $li.position();
                    switch(this.settings.taskbarMode) {
                        case 'left':
                        case 'right':
                            if (pos.left!==0)
                            this.elems.taskItems.scrollLeft(pos.left);
                            break;
                        case 'top':
                        case 'bottom':
                        default:
                            if (pos.top!==0)
                                this.elems.taskItems.scrollTop((swui.taskbar.configs.taskPositionY||0)+pos.top);
                            break;
                    }
                }
            }
            //打开窗口的方法（可自己根据需求来写）
            ,OpenWindow: function(option,index) {
                if (this.Utils.isString(option)) {
                    if (option === 'setting') {
                        option = {code:'setting',icon:'<fa>fa-cog',id:'swui-setting',title:'设置',showMax:true,url:swui.path + swui.setter.Page.theme,noIframe:true,index:index};
                    }
                }
                if (option === 'helper' || option.code === 'helper') {
                    swui.helper.open();
                    swui.live2d.open();
                    return;
                }
                else if (option === 'browser') {
                    option = layxwin.openBrowserWindow({code: 'browser'},true);
                }
                else if (option.code === 'browser') {
                    option = layxwin.openBrowserWindow(option, index === 1);
                    if (option === true) return;
                }
                else if (!option.url || !option.title) {
                    layer.msg('菜单配置错误（菜单链接、标题缺一不可）');
                    return;
                }
                swui.taskbar.addTaskItem(option, function(id, elem, isnew){
                    if (!isnew) {
                        //tab页面专用index来指定跳到哪个tab选项卡
                        if (index != null) $("#layx-"+id+" .swui-tab-nav").children('li').eq(index).click();
                        return;
                    }
                    var op = $.extend({}, option, {
                        id: id,
                        relateElem: elem[0],
                        relateCloseBtn: option.taskType !== 'icon'
                    });
                    op.event = $.extend({}, option.event, {
                        onfocus:function(){
                            swui.removeContextMenu();
                            swui.hideStartMenu();
                            swui.hideUserMenu();
                            swui.hideTaskIcon();
                            swui.hideConsole();
                            swui.setFocusWindow();
                        },
                        onmin:{
                            after: function (layxWindow, winform) { 
                                swui.setFocusWindow();
                            }
                        },
                        ondestroy:{
                            after:function(id, parent, elem){
                                swui.setFocusWindow();//前一任务项取得焦点
                                layxwin.endPreview();//预览关闭时，非最小化窗口重新显示
                                swui.taskbar.removeTaskItem({id: id,parent:$(parent).parent(),elem:$(elem)});
                            }
                        }
                    });
                    if (op.code === 'browser') op.icon = false;
                    else if (op.icon) {
                        op.icon = swui.getIconHtml(op.icon);
                    }
                    layxwin.open(op, function(win){
                        if (option.showMax) layxwin.max(win.id);
                        swui.setFocusWindow();
                    });
                    
                });
            }
        };

        window.swui = new SWUI();

        exports(swui.MOD_NAME, {});

        delete layui.swui;
    });
}(window);
